/*
 * Created by 岱青海蓝信息系统(北京)有限公司 on 17-7-3 下午4:00
 * Copyright (c) 2017. All rights reserved.
 */

package com.example.dqhl.jdmetro.fragment.Live;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.example.dqhl.jdmetro.R;
import com.example.dqhl.jdmetro.activities.LiveDetailActivity;
import com.example.dqhl.jdmetro.adapter.live.LiveCommonAdapter;
import com.example.dqhl.jdmetro.base.BaseFragment;
import com.example.dqhl.jdmetro.bean.User;
import com.example.dqhl.jdmetro.bean.live.LiveCommon;
import com.example.dqhl.jdmetro.config.Config;
import com.example.dqhl.jdmetro.config.Constant;
import com.example.dqhl.jdmetro.utils.Dlog;
import com.example.dqhl.jdmetro.utils.JsonUtils;
import com.example.dqhl.jdmetro.utils.JumpItent;
import com.example.dqhl.jdmetro.utils.Toastutils;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * description:直播汇 公共Fragment
 * autour:guanluocang
 * date:17/7/3 16:00
 */
public class LiveCommonFragment extends BaseFragment {

    @Bind(R.id.live_refresh_layout)
    TwinklingRefreshLayout live_refresh_layout;
    private Context context;
    //    @Bind(R.id.refreshLeayout)
//    SwipyRefreshLayout refreshLayout;
    @Bind(R.id.live_recycleView)
    RecyclerView live_recycleView;
    private List<LiveCommon> commonList = new ArrayList<>();
    private LiveCommonAdapter commonAdapter;
    private String theme_id = "";
    private int page = 1;

    @Override
    public View initView(LayoutInflater inflater) {
        rootView = inflater.inflate(R.layout.fragment_live_common, null);
        ButterKnife.bind(this, rootView);
        context = getActivity();
        theme_id = getArguments().getString("theme_id");
        registerBroadcastReceiver();
        LinearLayoutManager linearLayoutManager_list = new LinearLayoutManager(getActivity());
        linearLayoutManager_list.setOrientation(LinearLayoutManager.VERTICAL);
        live_recycleView.setLayoutManager(linearLayoutManager_list);
        live_recycleView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));

        return rootView;
    }

    /**
     * 广播接收者
     */
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Constant.ACTION_LOGIN_SUCCESS)) {
                user = (User) intent.getExtras().get("user");
                Dlog.e(user.toString());
            } else if (action.equals(Constant.ACTION_LOGOUT_SUCCESS)) {
                user = null;
            }
        }
    };

    /**
     * 注册广播接收者
     */
    private void registerBroadcastReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_LOGIN_SUCCESS);
        intentFilter.addAction(Constant.ACTION_LOGOUT_SUCCESS);
        context.registerReceiver(receiver, intentFilter);
    }

    @Override
    public void initData() {
        commonAdapter = new LiveCommonAdapter(context);
        live_recycleView.setAdapter(commonAdapter);
        ProgressLayout headerView = new ProgressLayout(getActivity());
        live_refresh_layout.setHeaderView(headerView);
        live_refresh_layout.setOverScrollRefreshShow(false);
        doCommentList(page);

    }

    @Override
    public void initListener() {
        live_refresh_layout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                page = 1;
                doCommentList(page);
                refreshLayout.finishRefreshing();
            }

            @Override
            public void onLoadMore(final TwinklingRefreshLayout refreshLayout) {
                page++;
                loadMoreCommentList(page);
                refreshLayout.finishLoadmore();
            }
        });
    }

    public void doCommentList(int pages){
        showLoadingBar("");
        RequestParams params = new RequestParams(Config.live_data);
        params.addBodyParameter("theme_id", theme_id);
        params.addBodyParameter("page",pages+"");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("直播汇公共" + result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getData(result);
                String errMsg = JsonUtils.getErrMsg(result);
                if (errCode == 200) {
                    commonList = JSON.parseArray(data, LiveCommon.class);
                    commonAdapter.refresh_list(commonList);
                    commonAdapter.setOnItemClickListener(new LiveCommonAdapter.onItemClickListener() {
                        @Override
                        public void onItemClick(View view, int position) {
                            if (user != null) {
                                Bundle bundle = new Bundle();
                                bundle.putString("id", commonList.get(position).getId());
                                JumpItent.jump(getActivity(), LiveDetailActivity.class, bundle);
                            } else {
                                Toastutils.show("请先登录");
                            }

                        }
                    });
                } else {
                    Toastutils.show(errMsg);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideLoadingBar();
            }
        });
    }

    public void loadMoreCommentList(int pages){
        showLoadingBar("");
        RequestParams params = new RequestParams(Config.live_data);
        params.addBodyParameter("theme_id", theme_id);
        params.addBodyParameter("page",pages+"");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("直播汇公共" + result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getData(result);
                String errMsg = JsonUtils.getErrMsg(result);
                if (errCode == 200) {
                    commonList.addAll(JSON.parseArray(data, LiveCommon.class));
                    commonAdapter.refresh_list(commonList);
                } else {
                    Toastutils.show(errMsg);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideLoadingBar();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        if (receiver != null) {
            context.unregisterReceiver(receiver);
        }
    }
}
